package com.wangsb.code0404;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Description: TODO
 * @author: shenbing.wang@hand-china
 * @date: 2021年06月26日 22:30
 */
public class ClientTest {

    public static void main(String[] args) {
        Socket s = null;
        ObjectOutputStream ps = null;

        ObjectInputStream br = null;
        Scanner sc = null;
        try {
            // 1.创建Socket类型的对象并提供服务器的主机名和端口号
            s = new Socket("127.0.0.1", 8888);
            System.out.println("连接服务器成功！");

            // 2.使用输入输出流进行通信

            ps = new ObjectOutputStream(s.getOutputStream());
            br = new ObjectInputStream(s.getInputStream());

            while (true) {
                sc = new Scanner(System.in);
                System.out.println("请输入用户名： ");
                String str1 = sc.next();
                System.out.println("请输入密码 ");
                String str2 = sc.next();
                UserMessage userMessage = new UserMessage(new User(str1, str2), "check");
                // 实现客户端向服务器发送字符串内容"hello"
                ps.writeObject(userMessage);


                System.out.println("userMessage = " + userMessage);
                System.out.println("客户端发送数据内容成功！");
                // 实现接收服务器发来的字符串内容并打印
                UserMessage userMessage1 = (UserMessage) br.readObject();
                System.out.println("userMessage1 = " + userMessage1);
                if ("success".equals(userMessage1.getType())) {
                    System.out.println("登陆成功");
                    return;
                } else {
                    System.out.println("登陆失败，請重新登录");
                }

            }

        } catch (IOException /*| InterruptedException*/ e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 3.关闭Socket并释放有关的资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ps) {
                try {
                    ps.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (sc != null) {
                sc.close();
            }
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
